package com.m.job.server.service.impl;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.client.job.core.constant.JobInstanceStatus;
import com.client.job.core.model.MJob;
import com.client.job.utils.SnowflakeIdWorker;
import com.m.job.compents.SocketJobForCLientComponent;
import com.m.job.server.mapper.MJobInstanceMapper;
import com.m.job.server.mapper.MJobMapper;
import com.m.job.server.model.MJobInstanceDto;
import com.m.job.server.service.MJobService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * JobService
 * 
 * @author monxz
 * @version 2021-07-18
 */
@Service
@Transactional
public class MJobServiceImpl implements MJobService {

	@Autowired
	private MJobMapper jobMapper;

	@Autowired
	private MJobInstanceMapper jobInstanceMapper;

	@Autowired
	private SocketJobForCLientComponent socketJobForCLientComponent;

	@Override
	public List<MJob> findJobDetailList(MJob JobDetail) {
		return jobMapper.getList(JobDetail);
	}
	@Override
	public MJob getById(String jobId) {
		return jobMapper.get(jobId);
	}


	@Override
	public Integer addJobDetail(MJob JobDetail) {
		JobDetail.setJobId(SnowflakeIdWorker.genId(1, 1));
		return jobMapper.insert(JobDetail);
	}

	@Override
	public Integer modifyJobDetail(MJob mJob) {
		MJob  oldJob = jobMapper.get(mJob.getJobId());
		if(oldJob.getJobName().equals(mJob.getJobName())
			&& oldJob.getJobCode().equals(mJob.getJobCode())
			&& oldJob.getCron().equals(mJob.getCron()) 
			&& oldJob.getKeyName().equals(mJob.getKeyName())
			&& oldJob.getZone() == mJob.getZone()
			&& oldJob.getToLong().equals(mJob.getToLong())) {
			return 0 ;
		}
		jobMapper.update(mJob);
		List<MJobInstanceDto> runList = jobInstanceMapper.getListByJobIds(Arrays.asList(oldJob.getJobId()),
				JobInstanceStatus.SERVER_RUNNING.getStatus(), JobInstanceStatus.JOB_RUNNING.getStatus());
		socketJobForCLientComponent.updAppCounts(Arrays.asList(mJob),MJobInstanceDto.dtoListToPoList( runList));
		return 1;
	}

	@Override
	public Integer remove(String jobId) {
		return jobMapper.delete(jobId);
	}

	@Override
	public String checkUnion(MJob JobDetail) {
		MJob check = new MJob();
		check.setJobCode(JobDetail.getJobCode());
		List<MJob> JobDetailList = jobMapper.getExctList(check);
		if (JobDetailList == null || JobDetailList.isEmpty()) {
			return null;
		}
		if (JobDetailList.size() > 1) {
			return "数据重复";
		}
		if (!JobDetail.getJobId().equals(JobDetailList.get(0).getJobId())) {
			return "数据重复";
		}
		return null;
	}

	@Override
	public List<MJob> listJobByJobIds(List<String> jobIds) {
		return jobMapper.getListByIds(new HashSet<>(jobIds));
	}

	
}